<template>
	<div class="detail-payment">
		<div style=" width: 100%;display: flex;justify-content: space-between;">
			<div style="display: flex">
				<el-date-picker v-model="selectDate" :type="dateType" placeholder="选择日期" @change="changeDate"
					:clearable="false">
				</el-date-picker>
				<el-select v-model="dateType" style="width: 80px;" @change="changeType">
					<el-option value="year" label="年"></el-option>
					<el-option value="month" label="月"></el-option>
					<el-option value="date" label="日"></el-option>
				</el-select>
				<el-button type="primary" @click="exportExcel" style="margin-left: 10px;" v-debounce>
					导出Excel
				</el-button>
			</div>
			<!-- 条件查询 -->
			<div style="display: flex;">
				<div v-if="userInfo.roleId === '1'" style="line-height: 40px;">
					<span>总计金额：{{ totalAmount }}</span>
				</div>
				<el-select v-model="userId" filterable remote clearable :loading="userLoading"
					:remote-method="getUserList" placeholder="按业务员搜索" style="margin-left: 10px; width: 150px;"
					@change="onSubmit" @focus="getUserList('')">
					<el-option v-for="item in userList" :key="item.id" :label="item.nickName" :value="item.id">
					</el-option>
				</el-select>
				<el-select v-model="accountId" filterable remote clearable :loading="accountLoading" placeholder="按账户搜索"
					@change="onSubmit" :remote-method="getAccountList" @focus="getAccountList('')"
					style="margin-left: 10px; width: 250px;">
					<el-option v-for="item in accountList" :key="item.id" :label="item.account" :value="item.id">
					</el-option>
				</el-select>
				<el-button @click="reset" style="margin-left: 10px;" v-debounce>重置</el-button>
			</div>
		</div>
		<div class="data-table">
			<el-table :data="tableData" v-loading="loading" border stripe style="width: 100%" height="100%">
				<el-table-column prop="i" label="序号" width="50">
				</el-table-column>
				<el-table-column prop="sn" label="订单流水号" width="150">
				</el-table-column>
				<el-table-column prop="nickName" label="业务员" width="80">
				</el-table-column>
				<el-table-column prop="amount" label="收款金额" width="80">
				</el-table-column>
				<el-table-column prop="repaymentDate" label="收款日期" width="100">
				</el-table-column>
				<el-table-column prop="fundsReceived" label="实收金额" width="80">
				</el-table-column>
				<el-table-column prop="dateReceived" label="实收日期" width="170">
				</el-table-column>
				<el-table-column prop="account" label="收款账户" fit>
				</el-table-column>
			</el-table>
			<el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
				:current-page="currentPage" :page-sizes="[20, 50, 100]" :page-size="pageSize"
				layout="total, sizes, prev, pager, next, jumper" :total="total">
			</el-pagination>
		</div>
	</div>
</template>

<script>
import orderApi from "../../api/order.js";
import userApi from "../../api/user.js"
import financeApi from "../../api/financeManage.js";
export default {
	data() {
		return {
			userInfo: {},
			tableData: [],
			loading: false,
			currentPage: 1,
			pageSize: 50,
			total: 0,
			userId: null,
			userList: [],
			userLoading: false,
			year: null,
			yearMonth: null,
			yearMonthDay: null,
			selectDate: null,
			dateType: "month",
			totalAmount: null,
			accountId: null,
			accountList: [],
			accountLoading: false,
		};
	},
	created() {
		this.userInfo = JSON.parse(localStorage.getItem("userInfo"))
		this.initializeDate();
		this.getBillingList();
	},
	methods: {
		initializeDate() {
			const currentYear = new Date().getFullYear();
			let currentMonth = new Date().getMonth() + 1;
			let currentDay = new Date().getDate()
			currentMonth = currentMonth < 10 ? '0' + currentMonth : currentMonth;
			currentDay = currentDay < 10 ? '0' + currentDay : currentDay;
			this.yearMonth = `${currentYear}-${currentMonth}`
			this.selectDate = this.yearMonth;
		},
		// 获取账单列表
		getBillingList() {
			this.loading = true
			const data = {
				userId: this.userId,
				year: this.year,
				yearMonth: this.yearMonth,
				yearMonthDay: this.yearMonthDay,
				account: this.accountId,
				currentPage: this.currentPage,
				pageSize: this.pageSize,
			}
			orderApi.getBillingList(data).then(res => {
				if (res.code === 200) {
					this.total = res.data.total
					this.totalAmount = res.data.totalAmount
					if (res.data.orderBillingVoList) {
						this.tableData = res.data.orderBillingVoList.map((item, index) => {
							item.i = (this.currentPage - 1) * this.pageSize + index + 1;
							return item;
						})
					}
					this.loading = false
				}
			})
		},
		// pageSize变化
		handleSizeChange(pageSize) {
			this.pageSize = pageSize
			this.getBillingList()
		},
		// 页码变化
		handleCurrentChange(curPage) {
			this.currentPage = curPage
			this.getBillingList()
		},
		// 日期类型改变
		changeType() {
			this.selectDate = new Date();
			this.changeDate();
		},
		// 日期改变
		changeDate() {
			//console.log("选择的日期==>",this.selectDate)
			this.year = null;
			this.yearMonth = null;
			this.yearMonthDay = null;
			if (this.selectDate !== null) {
				const year = this.selectDate.getFullYear();
				const month = this.selectDate.getMonth() + 1; // 月份从 0 开始，需要加 1
				const day = this.selectDate.getDate();
				// 格式化月份和日期，确保始终是两位数
				const formattedMonth = month < 10 ? '0' + month : month;
				const formattedDay = day < 10 ? '0' + day : day;
				if (this.dateType === "year") {
					this.year = year;
				} else if (this.dateType === "month") {
					this.yearMonth = `${year}-${formattedMonth}`;
				} else {
					this.yearMonthDay = `${year}-${formattedMonth}-${formattedDay}`;
				}
			}
			this.onSubmit();
		},
		// 条件查询提交
		onSubmit() {
			this.currentPage = 1
			this.pageSize = 50
			this.getBillingList()
		},
		// 远程搜索业务员
		async getUserList(query) {
			this.userLoading = true;
			const data = {
				nickName: query,
				roleId: 3,
			}
			let r3 = await userApi.fuzzyQuery(data)
			data.roleId = 1
			let r1 = await userApi.fuzzyQuery(data)
			data.roleId = 7
			let r7 = await userApi.fuzzyQuery(data)
			this.userList = [...r3.data.userVoList, ...r1.data.userVoList, ...r7.data.userVoList];
			this.userLoading = false;
		},
		// 远程搜索账户
		getAccountList(query) {
			this.accountLoading = true;
			const data = {
				accountName: query,
				currentPage: 1,
				pageSize: 10,
			}
			financeApi.getAccountList(data).then(res => {
				if (res.code === 200) {
					this.accountList = res.data.accountList
				}
			}).finally(() => {
				this.accountLoading = false;
			})
		},
		// 重置查询条件
		reset() {
			this.userId = null
			this.accountId = null
			this.dateType = "month"
			this.changeType();
		},
		//导出Excel
		exportExcel() {
			const data = this.formatData(this.tableData); // 将数据格式化为xlsx可以识别的格式
			const wb = this.$XLSX.utils.book_new();
			const ws = this.$XLSX.utils.json_to_sheet(data);
			// 设置列宽
			const columnWidths = [
				{ wch: 5 }, // 序号
				{ wch: 25 }, // 订单流水号
				{ wch: 10 }, // 业务员
				{ wch: 10 }, // 付款金额
				{ wch: 15 }, // 付款日期
				{ wch: 10 }, // 实付金额
				{ wch: 20 }, // 实付日期
				{ wch: 25 } // 付款账户
			];
			ws['!cols'] = columnWidths;
			this.$XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
			let fileName = "收款明细";
			if (this.dateType === "year") {
				fileName = this.year + "收款明细";
			} else if (this.dateType === "month") {
				fileName = this.yearMonth + "收款明细";
			} else {
				fileName = this.yearMonthDay + "收款明细";
			}
			this.$XLSX.writeFile(wb, fileName + ".xlsx");
		},
		formatData(data) {
			// 格式化表格数据，将对象数组转换为数组对象
			return data.map((item) => {
				const {
					i,
					sn,
					nickName,
					amount,
					repaymentDate,
					fundsReceived,
					dateReceived,
					account
				} = item;
				return {
					序号: i,
					订单流水号: sn,
					业务员: nickName,
					收款金额: amount,
					收款日期: repaymentDate,
					实收金额: fundsReceived,
					实收日期: dateReceived,
					收款账户: account,
				};
			});
		},
	}
}
</script>

<style>
.detail-payment {
	height: 100%;
}

.data-table {
	height: 94%;
	display: flex;
	flex-direction: column;
	align-items: flex-end;
	justify-content: center;
	margin-top: 10px;
}
</style>